<?php
namespace Common\Model;
use Think\Model;
class ProductsModel extends Model {
    private $_db = '';

    public function __construct() {
        $this->_db = M('products');
    }
 public function select($data = array(), $limit = 100) {

        $conditions = $data;
        $list = $this->_db->where($conditions)->order('products_id desc')->limit($limit)->select();
        return $list;
    }
   public function insert($data=array()){
       if(!is_array($data)||!$data){
       	return 0;
       }
      $data['create_time']=time();
      $data['username'] =  getLoginUsername();
      return   $this->_db->add($data);
   }
public function getProducts($data,$page,$pageSize=10) {
        $conditions = $data;
        if(isset($data['products_name']) && $data['products_name']) {
            $conditions['products_name'] = array('like','%'.$data['products_name'].'%');
        }
        $conditions['status'] = array('neq',-1);

        $offset = ($page - 1) * $pageSize;
        $list = $this->_db->where($conditions)
            ->order('listorder desc,products_id desc')
            ->limit($offset,$pageSize)
            ->select();

        return $list;

    }


    public function getProductsCount($data = array()){
        $conditions = $data;
        if(isset($data['products_name']) && $data['products_name']) {
            $conditions['products_name'] = array('like','%'.$data['products_name'].'%');
        }

        $conditions['status'] = array('neq',-1);

        return $this->_db->where($conditions)->count();
    }
    public function find($id) {
        $data=$this->_db->where('products_id='.$id)->find();
        return $data;
    }

  public function updateById($id, $data) {
        if(!$id || !is_numeric($id) ) {
            throw_exception("ID不合法");
        }
        if(!$data || !is_array($data)) {
            throw_exception('更新数据不合法');
        }

        return $this->_db->where('products_id='.$id)->save($data);
    }


    public function updateStatusById($id, $status) {
        if(!is_numeric($status)) {
            throw_exception('status不能为非数字');
        }
        if(!$id || !is_numeric($id)) {
            throw_exception('id不合法');
        }
        $data['status'] = $status;

        return $this->_db->where('products_id='.$id)->save($data);
    }

    public function updateProductsListorderById($id, $listorder) {
        if(!$id || !is_numeric($id)) {
            throw_exception('ID不合法');
        }
        $data = array('listorder'=>intval($listorder));
        return $this->_db->where('products_id='.$id)->save($data);
    }






}   